<template>
  <div class="modal">
    <!-- 浙罩层 -->
    <div class="mask" @click="changIsShowLoginModal(false)"></div>
    <!-- 登录框 -->
    <div class="login">
      <!-- 关闭按钮 -->
      <div class="close" @click="changIsShowLoginModal(false)"></div>
      <!-- 手机登录和微信登录 -->
      <div class="navs">
        <a
          href="#"
          :class="{ active: isShowLoginContent }"
          @click="isShowLoginContent = true"
          >手机号登录</a
        >|
        <a href="#" :class="{ active: !isShowLoginContent }" @click="showQrCode"
          >微信登录</a
        >
      </div>
      <!-- 内容 -->
      <div class="content">
        <!-- 手机号登录 -->
        <div class="phoneLogin" v-show="isShowLoginContent">
          <div class="row">
            <input
              type="text"
              placeholder="请输入手机号"
              class="ipt"
              v-model="phoneNumber"
            />
          </div>
          <div class="row">
            <slide-verify
              :l="42"
              :r="20"
              :w="362"
              :h="140"
              @success="onSuccess"
              @fail="onFail"
              @refresh="onRefresh"
              :style="{ width: '100%' }"
              class="slide-box"
              ref="slideBlock"
              :slider-text="msg"
              :imgs="arr"
              :accuracy="10"
            ></slide-verify>
          </div>
          <div class="row">
            <input
              type="text"
              placeholder="请输入短信验证码"
              class="ipt"
              v-model="code"
            />
            <button class="btn btncode" @click="getCode" v-show="!isShowCount">
              获取验证码
            </button>
            <button class="btn btncode" v-show="isShowCount">
              重新获取 ({{ count }})
            </button>
          </div>
          <div class="row">
            <div class="btn btnlogin" @click="LoginFn">登录</div>
          </div>
        </div>
        <!-- 微信登录 -->
        <div class="qrLogin" v-show="!isShowLoginContent" id="weixin"></div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapMutations, mapActions } from "vuex";
import { validatePhoneNumber } from "@/utils/index.js";
import {
  SendSMSAPI,
  PhoneReginAPI,
  BindingAPI,
  UserProfilesAPI,
} from "@/request/api.js";
export default {
  //二维码失效优化
  mounted() {
    if (this.$route.query.code) {
      this.isShowLoginContent = false;
      //清除code
      this.$router.push(this.$route.path);
    }
    let _this = this;
    new WxLogin({
      id: "weixin",
      appid: "wx67cfaf9e3ad31a0d", // 这个appid要填死
      scope: "snsapi_login",
      // 扫码成功后重定向的接口
      redirect_uri: "https://sc.wolfcode.cn/cms/wechatUsers/shop/PC",
      // state填写编码后的url
      state: encodeURIComponent(
        window.btoa("http://127.0.0.1:8080" + _this.$route.path)
      ),
      // 调用样式文件
      href: "data:text/css;base64,LmltcG93ZXJCb3ggLnRpdGxlLC5pbXBvd2VyQm94IC5pbmZvew0KICAgIGRpc3BsYXk6IG5vbmU7DQp9ICAgIA0KLmltcG93ZXJCb3ggcXJjb2Rlew0KICAgIG1hcmdpbi10b3A6IDIwcHg7DQp9",
    });
  },
  data() {
    return {
      isShowLoginContent: true,
      msg: "向右滑动",
      phoneNumber: "",
      count: 5,
      isShowCount: false,
      arr: [
        require("../assets/img/integral-01.9386d4bf.png"),
        require("../assets/img/integral-02.150d92a1.png"),
        require("../assets/img/integral-03.9870f3f1.png"),
        require("../assets/img/integral-04.afadcbdf.png"),
      ],
      //验证码
      code: "",
    };
  },
  methods: {
    ...mapMutations({
      changIsShowLoginModal: "showModel/changIsShowLoginModal",
      changIisLogined: "loginStatus/changIisLogined",
      // changIsShowToast: "showToast/changIsShowToast",
    }),
    ...mapActions({
      asyncIsShowToast: "showToast/asyncIsShowToast",
      asyncChangeUserInfo: "userInfo/asyncChangeUserInfo",
    }),
    // 拼图成功
    onSuccess(times) {
      let ms = (times / 1000).toFixed(1);
      this.msg = "login success, 耗时 " + ms + "s";
    },
    // 拼图失败
    onFail() {
      this.onRefresh(); // 重新刷新拼图
    },
    // 拼图刷新
    onRefresh() {
      this.msg = "再试一次";
    },
    //封装一个校验手机号码和滑块验证码
    toVerfiy() {
      //1.验证手机号码。
      if (!validatePhoneNumber(this.phoneNumber)) {
        // alert("请输入正确的手机号码!");
        //-------------------
        // this.changIsShowToast({
        //   isShow: true,
        //   title: "请输入正确的手机号码",
        //   type: "danger",
        // });
        // setTimeout(() => {
        //   this.changIsShowToast({
        //     isShow: false,
        //   });
        // }, 1000);
        //---------------
        this.asyncIsShowToast({
          isShow: true,
          title: "请输入正确的手机号码",
          type: "danger",
        });
        return;
      }
      // 2.验证滑块验证码 不成功是再试一次或者向右滑动
      if (this.msg == "再试一次" || this.msg == "向右滑动") {
        // alert("请重新滑动滑块验证码");
        this.asyncIsShowToast({
          isShow: true,
          title: "请重新滑动滑块验证码",
          type: "danger",
        });
        return;
      }
      return true;
    },
    //获取验证码
    async getCode() {
      let flag = this.toVerfiy(); //当这个方法验证成功后，才能继续后面的操作
      if (!flag) return; //如果校验不通过，则return
      let res = await SendSMSAPI({
        phone: this.phoneNumber,
      });
      console.log("res", res);
      if (!res) return;
      if (res.code == 0) {
        // console.log("发送成功");
        this.asyncIsShowToast({
          isShow: true,
          title: "发送成功",
          type: "success",
        });
        //3.发送验证码
        this.isShowCount = true;
        let timer = setInterval(() => {
          this.count--;
          if (this.count == 0) {
            clearInterval(timer);
            this.count = 5;
            this.isShowCount = false;
          }
        }, 1000);
      }
    },
    //登录成功
    async LoginFn() {
      //1.验证手机号码
      //2.验证滑块验证码
      if (!this.toVerfiy()) return;
      // 3.验证手机验证码
      if (this.code == "") {
        // alert("请输入手机验证码");
        this.asyncIsShowToast({
          isShow: true,
          title: "请输入手机验证码",
          type: "danger",
        });
        return;
      }
      let uuid = localStorage.getItem("uuid");
      let res = null;
      if (uuid) {
        res = await BindingAPI({
          verifyCode: this.code,
          phone: this.phoneNumber,
          uuid,
        });
      } else {
        res = await PhoneReginAPI({
          verifyCode: this.code,
          phone: this.phoneNumber,
        });
      }

      if (!res) return;
      console.log("登录成功", res);
      if (res.code == 0) {
        // 1.提示登录成功
        // alert("登陆成功");
        this.asyncIsShowToast({
          isShow: true,
          title: "登录成功",
          type: "success",
        });
        //2.存储token
        localStorage.setItem("x-auth-token", res["x-auth-token"]);
        //3.关闭登录模态框
        uuid && this.changIsShowLoginModal(false);
        // 4.登录框换为购物车
        uuid && this.changIisLogined(true);
        //1.删除uuid
        localStorage.removeItem("uuid");
        //2.删除地址栏的code
        this.$router.push(this.$route.path);
        this.asyncChangeUserInfo();
      }
    },
    showQrCode() {
      this.isShowLoginContent = false;
      // 申请微信登录二维码
    },
  },
};
</script>

<style lang="less" scoped>
.modal {
  width: 100%;
  height: 100%;
  position: fixed;
  left: 0;
  top: 0;
  .mask {
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.4);
  }
  .login {
    position: absolute;
    inset: 0;
    margin: auto;
    width: 555px;
    height: 423px;
    background: url("../assets/img/login-box-bg.png");
    .close {
      position: absolute;
      top: 10px;
      right: 60px;
      width: 22px;
      height: 22px;
      background: url("../assets/img/close.png");
    }
    .navs {
      display: flex;
      justify-content: center;
      margin-top: 40px;
      a {
        color: #ccc;
        text-decoration: none;
        padding: 0 20px;
        &.active {
          color: #000;
        }
      }
    }
    .content {
      width: 355px;
      margin: 20px auto;
      .phoneLogin {
        .row {
          display: flex;
          margin-bottom: 25px;
        }
        .ipt {
          flex: 1;
          height: 50px;
          text-indent: 1em;
          outline: none;
        }
        .btn {
          background-color: rgb(10, 50, 142);
          color: #fff;
          border: none;
        }
        .btncode {
          margin-left: 10px;
          width: 80px;
        }
        .btnlogin {
          width: 100%;
          height: 50px;
          text-align: center;
          line-height: 50px;
        }
      }
      .qrLogin {
        text-align: center;
      }
    }
  }
}

/deep/.slide-box {
  width: 100%;
  position: relative;
  box-sizing: border-box;
  canvas {
    position: absolute;
    left: 0;
    top: -120px;
    display: none;
    width: 100%;
    box-sizing: border-box;
  }
  .slide-verify-block {
    width: 85px;
    height: 136px;
  }
  .slide-verify-refresh-icon {
    top: -120px;
    display: none;
  }
  &:hover {
    canvas {
      display: block;
    }
    .slide-verify-refresh-icon {
      display: block;
    }
  }
}
</style>